import { Popover } from 'ant-design-vue';
import { ColorPicker } from 'vue-color-kit';
import { App, defineComponent, h, ref } from 'vue';
import './color-picker.less';

/**
 * 颜色选择器
 */
const AColorPicker = defineComponent({
  name: 'AColorPicker',
  inheritAttrs: false,
  props: {
    value: {
      type: String,
      default: '#FFFFFF',
    },
  },
  emits: ['update:value', 'change'],
  setup(props, context) {
    let pointColor = props.value || '';
    const visible = ref(false);
    let colorObject: any = null;

    const changeColor = (color: any) => {
      pointColor = color.hex;
      colorObject = color;
    };
    const cancel = () => {
      visible.value = false;
      pointColor = props.value;
    };
    const choose = () => {
      visible.value = false;
      context.emit('update:value', pointColor);
      context.emit('change', colorObject);
    };

    const Buttons = [
      h(
        'button',
        { size: 'small', onClick: choose, class: 'btn' },
        {
          default: () => '确定',
        },
      ),
      h(
        'button',
        { size: 'small', class: 'ml5', onClick: cancel },
        {
          default: () => '取消',
        },
      ),
    ];

    const content = [
      h(
        ColorPicker,
        {
          suckerHide: false,
          color: pointColor,
          onChangeColor: changeColor,
        } as any /* TODO 强制给any类型 */,
      ),
      h('div', { class: 'f-tac' }, Buttons),
    ];

    return () =>
      h(
        Popover,
        {
          trigger: 'click',
          placement: 'right',
          visible: visible.value,
          'onUpdate:visible': (v: boolean) => {
            visible.value = v;
          },
          color: 'rgb(34, 44, 69)',
        },
        {
          default: () =>
            h('div', { class: 'marsColorView', style: { backgroundColor: props.value } }),
          content: () => h('div', null, content),
        },
      );
  },
});

export function install(app: App): App {
  app.component(AColorPicker.name, AColorPicker);
  return app;
}
export default AColorPicker;
